﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    startReceiver();
}

Widget::~Widget()
{
    stopReceiver();

    delete ui;
}

void Widget::startReceiver()
{
    receiver=new BaseReceiver(0,true,P_PORT);
    connect(receiver,&BaseReceiver::received,this,&Widget::onReceived);
    connect(&recvThread,&QThread::finished,receiver,&QObject::deleteLater);
    receiver->moveToThread(&recvThread);
    recvThread.start();
}

void Widget::stopReceiver()
{
    recvThread.quit();
    recvThread.wait();
}

void Widget::onReceived(const QByteArray &data)
{
    QJsonDocument doc=QJsonDocument::fromJson(data);
    if(doc.isObject())
    {
        QJsonObject obj=doc.object();
        QString url=obj.value("url").toString();
        if(url != selectUrl)
            return;

        QString label=obj.value("label").toString();
        QString detail=obj.value("detail").toString();
        if(label.isEmpty() || detail.isEmpty())
            return;

        QSqlQuery query;
        query.exec(QString("select label from %1 where detail='%2'")
                   .arg(G_FETCH).arg(detail));
        if(query.next())
        {
            QString status=url + " [Finishd]";
            ui->status->setText(status);
        }
        else
        {
            qApp->clipboard()->setText(detail);

            query.prepare(QString("insert into %1 (label,detail,addition) values (?,?,?)")
                          .arg(G_FETCH));
            query.addBindValue(label);
            query.addBindValue(detail);
            query.addBindValue(url);
            if(!query.exec())
                qDebug()<< query.lastError().text();
        }
    }
}

void Widget::on_btn_paste_clicked()
{
    QString url=qApp->clipboard()->text();
    if(!url.isEmpty())
        ui->url->setText(url);
}

void Widget::on_btn_parser_clicked()
{
    selectUrl=ui->url->text().trimmed();
    if(selectUrl.isEmpty())
        return;

    if(!selectUrl.startsWith("http"))
    {
        ui->status->setText("Only Support Web URL");
        ui->url->clear();
        return;
    }

    QString host=QUrl(selectUrl).host();
    QSqlQuery query;
    query.exec(QString("select detail from %1 where label like '%%2%'")
               .arg(G_LINK).arg(host));
    if(query.next())
    {
        QString detail=query.value("detail").toString();
        QString py_file=P_FHS_SCRIPT + detail;
        if(QFile::exists(py_file))
        {
            QProcess::startDetached("python3",QStringList()<< py_file << selectUrl);
        }
    }
    else
        ui->status->setText("Not Support URL");
}
